// import { getShopList } from '@/services/getShopList';
// import { changeShopStatus } from '@/services/onOffline';
import { DeleteOutlined, LogoutOutlined, PlusOutlined, PoweroffOutlined, ShopOutlined } from '@ant-design/icons';
import { ActionType, ProLayout, ProTable } from '@ant-design/pro-components';
import { Button, Dropdown, Menu, Modal, Popconfirm, Space, message } from 'antd';
import React, { useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import DetailForm from './components/detailForm';
import "./components/myTable.css"
import { history } from '@umijs/max';
import { deleteShopsUsingDelete, pageQueryUsingPost } from '@/services/yu/shangpinxiangguanjiekou';
// import {pageQueryUsingPost} from "@/services/yu/shangpinxiangguanjiekou";
// import { queryProducts, updateProductStatus, deleteProduct,deleteProductAll } from './services/product'; // 假设有一个服务文件来处理数据请求和操作

interface TableRef {
  reload: () => Promise<void>;
}

const ProductList: React.FC = () => {

  const actionRef = useRef<TableRef>();
  // const actionRef = useRef<ActionType | undefined>(undefined);

  const [selectedProduct,setSelectedProduct]=useState(null)



  //新建商品modal
  const [createModalVisible, setCreateModalVisible] = useState(false);
  // 打开新建Modal页
  const handleOpenModal = () => {
    setCreateModalVisible(true);
  };
  // 关闭新建Modal页
  const handleCancel = () => {
    setCreateModalVisible(false);
  };

  //商品详情modal
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const showDetailModal = (record: any) => {
    console.log(record);
     setSelectedProduct(record);
    setDetailModalVisible(true);
  };
  const handleDetailModalCancel = () => {
    setDetailModalVisible(false);
  }

  //0:上线 1：下线 2：草稿 3：待审核 4：审核通过 5：审核驳回
  // 处理上下线状态更新
  const handleStatusChange = async (id: any, status: any) => {
    console.log(id, status);
    // try {
    //   const res = await changeShopStatus(id, status);
    //   if (res.code === 200) {
    //     //刷新
    //     message.success('更新成功');
    //     actionRef.current?.reload();
    //     console.log(id, status);
    //   } else {
    //     console.error('修改商品状态失败：', res.message);
    //   }
    // } catch (error) {
    //   console.error('修改商品状态失败：', error);
    // }
  };

  // 处理删除商品
  const handleDeleteProduct = async (id: any) => {

    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该商品吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
           await deleteShopsUsingDelete(id);
          message.success('删除商品成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除商品失败');
        }
      },
    });
  };

  // 处理批量删除商品
  const handleBatchDelete =  (selectedRowKeys:any) => {
    console.log('这个是删除的key',selectedRowKeys);
    // Modal.confirm({
    //   title: '确认批量删除',
    //   content: '确定要删除选中的商品吗？',
    //   okText: '确认',
    //   cancelText: '取消',
    //   onOk: async () => {
    //     try {
    //        const res=await deleteShopsUsingDelete(selectedRowKeys)
    //       if (res.code === 200) {
    //         message.success('批量删除商品成功');
    //         actionRef.current?.reload(); // 重新加载表格数据
    //       }
    //       message.success('批量删除商品成功');
    //     } catch (error) {
    //       message.error('批量删除商品失败');
    //     }
    //   },
    // });
  };
  //protable的columns
  const columns = [
    {
      title: '权益ID',
      dataIndex: 'id',
    },
    {
      title: '商品名称',
      dataIndex: 'shopName',
      render: (text: any, record: any) => (
        <a onClick={() => showDetailModal(record)}>{text}</a>
      ),
    },
    {
      hideInSearch: true,
      title: '库存',
      dataIndex: 'stock',
    },
    {
      title: '开始时间',
      dataIndex: 'onlineTime',
      valueType: 'date',
    },
    {
      title: '结束时间',
      dataIndex: 'offlineTime',
      valueType: 'date',
    },
    {
      title: '商品状态',
      dataIndex: 'status',
      valueEnum: {
        //0:上线 1：下线 2：草稿 3：待审核 4：审核通过 5：审核驳回
        0: { text: '已上线', status: 'Success' },
        1: { text: '已下线', status: 'Default' },
        2: { text: '草稿', status: 'Warning' },
        3: { text: '待审核', status: 'Processing' },
        4: { text: '审核通过', status: 'Success' },
        5: { text: '审核驳回', status: 'Error' },
      },
    },
    {
      title: '管理人',
      dataIndex: 'createUser',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => [
        <Popconfirm
          key="edit"
          title={record.status === 1 ? '确认要下线吗？' : '确认要上线吗？'}
          onConfirm={() => handleStatusChange(record.id, record.status)}
          okText="确认"
          cancelText="取消">
          {(record.status === 0 || record.status === 1) && (
            <Button type={record.status === 1 ? 'primary' : 'default'}>
             { (record.status === 1 )&&<ShopOutlined />}

             { (record.status === 0 )&&  <PoweroffOutlined />}
              {record.status === 1 ? '上线' : '下线'}
            </Button>
          )}
        </Popconfirm>,

        <Button style={(record.status === 0 || record.status === 1)? {} : {marginLeft:83}}
          key="delete"
          danger
          type="primary"
          onClick={() => handleDeleteProduct(record.id)}>
          <DeleteOutlined />删除
        </Button>,
      ],
    },
  ];

  const rowClassName = (record:any) => {
    let className = ''; // 初始化 className

    switch (record.status) {
      case 2: // 草稿
        className = 'draft-row'; // 对应自定义样式表中的 .draft-row
        break;
      case 4: // 审核通过
        className = 'approved-row'; // 对应自定义样式表中的 .approved-row
        break;
      case 1: // 下线
        className = 'offline-row'; // 对应自定义样式表中的 .offline-row
        break;
      default:
        break;
    }

    return className;
  };

  const CustomAvatarDropdown = ({ src, title, ...restProps }:any) => {


    const handleLogout = () => {
      // 在这里执行退出登录的逻辑，例如清除本地存储中的登录信息等

      console.log('退出登录');
      // 清除本地存储中的登录信息
      localStorage.removeItem('accessToken');

      // 重定向到登录页面
      history.push('/login');
    };

    return (
      <Dropdown
        menu={
          <Menu>
            <Menu.Item key="logout" onClick={handleLogout}>
              <LogoutOutlined />
              退出登录
            </Menu.Item>
          </Menu>
        }
        {...restProps}
      >
        <span>
          <img src={src} alt="avatar" style={{ width: '32px', borderRadius: '50%', marginRight: '8px' }} />
          {title}
        </span>
      </Dropdown>
    );
  };
  return (
    <>
        <ProLayout
        layout='top'
        //  avatarProps={{
        //   src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
        //   size: 'small',
        //   title: '七妮妮',
        //   render: (props, dom) => <CustomAvatarDropdown  {...props}>{dom}</CustomAvatarDropdown>,
        // }}
        headerTitleRender={(logo, title) => {
          return (
            <a>
            {logo}
            {title}
          </a>
          );

        }}


        >
        <ProTable

          headerTitle="商品列表"
          actionRef={actionRef}
          rowKey="id"
          rowClassName={rowClassName}
          rowSelection={{type: 'checkbox',}}

          tableAlertRender={({selectedRowKeys,selectedRows,onCleanSelected}) => {

            //打印一下
            console.log('+',selectedRowKeys,"xx", selectedRows);

            return (
              <Space size={24}>
                <span>
                  已选 {selectedRowKeys.length} 项
                  <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            );
          }}
          tableAlertOptionRender={({selectedRowKeys}) => {
            return (
              <Space size={16}>
                <Button type="primary" danger onClick={() => handleBatchDelete(selectedRowKeys)}>
                <DeleteOutlined />批量删除
                </Button>
              </Space>
            );
          }}
          search={{
            labelWidth: 120,
            defaultCollapsed: false,
            filterType: 'query',
          }}
          toolBarRender={() => [
            <Button key="add" type="primary" onClick={handleOpenModal}>
              <PlusOutlined /> 新增商品
            </Button>,
          ]}
          columns={columns}
          request={async (params: any) => {
            console.log('@@@@', params);
            const { current, pageSize,...query } = params;

            try {
              const res = await pageQueryUsingPost({page:current,pageSize});
              console.log('刷新了');
              return {
                data: res.data?.list,
                success: true,
                total: res.data?.total,
              };
            } catch (error) {
              console.error('获取商品列表失败：', error);
              return {
                data: [],
                success: false,
              };
            }
          }}
          options={{
            reload: () => actionRef.current?.reload(),
            fullScreen: false,
            setting: true,
            density: true,
          }}
          pagination={{ pageSize: 5 }}
        />
        {/* 新增或编辑商品的弹窗 */}
        <CreateForm modalVisible={createModalVisible} onCancel={handleCancel} />

        {detailModalVisible?<DetailForm
          modalVisible={detailModalVisible}
          onCancel={handleDetailModalCancel}
          product={selectedProduct}
        />:null}
        </ProLayout>

    </>
  );
};

export default ProductList;
